﻿//===============================================================================
// Magic OQL
//===============================================================================
// Copyright ?Magic Thought Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// Richie (http://www.cnblogs.com/RicCC)
// March 8, 2008
//===============================================================================

using System.Collections.Generic;
using Antlr.Runtime;
using Antlr.Runtime.Tree;

namespace SQLAnalyticLibrary.Expressions
{
    /// <summary>
    /// Select clause
    /// </summary>
    public class FromClause : Expression
    {
        #region constructors
        public FromClause(Expression node)
            : base(node.Token)
        {
            this._children = node._children;
        }
        public FromClause(IToken t)
            : base(t)
        {
        }
        #endregion

        public override Expression DupNode()
        {
            return new FromClause(this);
        }
        public override void VisitSql(ISqlVisitor visitor)
        {
            visitor.Sql(this.ToString()); //FROM keyword
            visitor.Space();
            //tables, joined tables
            for (int i = 0; this._children != null && i < this._children.Count; i++)
            {
                if (i != 0 && Table.IsTable(this._children[i])) visitor.Sql(",");
                else visitor.Space();
                this._children[i].VisitSql(visitor);
            }
        }

        public static bool IsFromClause(Expression exp)
        {
            if (exp == null || exp.IsNil) return false;
            return exp.Token.Type == OQLParser.FROM;
        }
        public IList<Table> Tables
        {
            get
            {
                IList<Table> r = new List<Table>();
                if (this._children == null || this._children.Count <= 0) return r;
                foreach (Expression exp in this)
                    if (Table.IsTable(exp)) r.Add(exp as Table);
                    else if (JoinedTable.IsJoinedTable(exp))
                    {
                        Table t = (exp as JoinedTable).GetTable();
                        if (t != null) r.Add(t);
                    }
                return r;
            }
        }
    }
}
